-- 提示进入tcp连接脚本
print("Device Start...")

isConn = false
islogin = false
connTim = 0 -- tcp尝试连接定时器
sendTim = 1 -- 定时发送定时器

-- 数据节点定义
LED_NODE = 1
ADC_NODE = 2

gpio.mode(0, gpio.OUTPUT) --LED IO口
gpio.write(0, gpio.HIGH)

-- tcp接收数据处理函数
function revCB(sck, data)
    t = sjson.decode(data)
    if (t.event == "login") then
        if (t.data == "success" and not islogin) then
            print("****login success****")
            islogin = true
            tmr.alarm(sendTim, 10000, 1, autoReport)
        else
            print("****login failed****")
        end
    elseif (t.event == "control") then
        if (t.node_id == LED_NODE) then
            if t.value then 
                gpio.write(0, gpio.LOW) -- 低电平点亮
            else
                gpio.write(0, gpio.HIGH)
            end
        autoReport()
        end
    end
end
-- tcp自动上报函数
function autoReport()
    json = {}
    json.event = "report"
    json.id = config.DEV_ID --好像不需要id了
    reportdata = {}
    if gpio.read(0)==0 then
        table.insert(reportdata, {["id"] = 1, ["value"] = true}) -- 0是低电平
    else
        table.insert(reportdata, {["id"] = 1, ["value"] = false})
    end
    -- table.insert(reportdata, {["id"] = 1, ["value"] = gpio.read(0)})
    table.insert(reportdata, {["id"] = 2, ["value"] = adc.read(0)})
    json.data = reportdata
    ok, ejson = pcall(sjson.encode, json)
    if ok then
        cl:send(ejson)
        print("send data:"..ejson)
    else
        print("failed to encode!")
    end
end

-- 连接成功回调
function connCB(conn, payload)
    print("\n****Connected****")
    tmr.stop(connTim)
    isConn = true
    json = {}
    json.event = "login"
    json.id = config.DEV_ID
    json.token = config.DEV_TOKEN
    ok, ejson = pcall(sjson.encode, json)
    if ok then
        cl:send(ejson)
    else
        print("failed to encode!")
    end
end

-- tcp断开回调
function disconnCB(conn, payload)
    print("\n****Disconnected****")
    islogin = false
    isConn = false
    -- 停止定时上报定时器
    tmr.stop(sendTim)
    tmr.alarm(
        connTim,
        10000,
        0,
        function()
            -- 减少重连次数？不知是否有用
            --if (not isConn) then
            print("\n****Try To Connect****")
            cl = net.createConnection(net.TCP, 0)
            cl:on("connection", connCB)
            cl:on("disconnection", disconnCB)
            cl:on("receive", revCB)
            cl:connect(config.serverport, config.serverip)
            --end
        end
    )
end

-- 创建连接对象
cl = net.createConnection(net.TCP, 0)
cl:on("connection", connCB)
-- tcp断开事件
cl:on("disconnection", disconnCB)
cl:on("receive", revCB)
cl:connect(config.serverport, config.serverip)
